﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication
{
    public partial class InterlockTest : Form
    {
        public InterlockTest()
        {
            InitializeComponent();
        }

        private void InterlockButton_Click(object sender, EventArgs e)
        {
            string output = string.Empty;
            for (int loop = 0; loop < 20; loop++)
            {
                sum = 0;
                Thread t1 = new Thread(Thread1);
                Thread t2 = new Thread(Thread2);
                t1.Start();
                t2.Start();

                t1.Join();
                t2.Join();
                output += "sum = " + sum+"\r\n";         // sum = 200000 ?
            }
            MessageBox.Show(output);
        }

        static int sum;
        static void Thread1()
        {
            for (int i = 0; i < 100000; i++) sum++;
        }
        static void Thread2()
        {
            for (int i = 0; i < 100000; i++) sum++;
        }

        //int padding = Interlocked.Add(ref _padding, 100);

        static int sum2;
        static void Thread3()
        {
            for (int i = 0; i < 100000; i++) 
            {
                //sum2++;
                Interlocked.Increment(ref sum2);
            }
        }
        static void Thread4()
        {
            for (int i = 0; i < 100000; i++)
            {
                //sum2++;
                Interlocked.Increment(ref sum2);
            }
        }

        private void InterlockEnableTest_Click(object sender, EventArgs e)
        {
            string output = string.Empty;
            for (int loop = 0; loop < 20; loop++)
            {
                sum2 = 0;
                Thread t1 = new Thread(Thread3);
                Thread t2 = new Thread(Thread4);
                t1.Start();
                t2.Start();

                t1.Join();
                t2.Join();
                output += "sum = " + sum2 + "\r\n";         // sum = 200000 ?
            }
            MessageBox.Show(output);

        }
    }
}
